<template>
  <div class="profile-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>我的个人中心</h1>
    </div>
    
    <!-- 用户信息卡片 -->
    <div class="user-profile-card">
      <div class="profile-header">
        <div class="avatar-container">
          <!-- 使用用户名第一个字作为默认头像 -->
          <div class="avatar-container">
            <img 
              v-if="user.avatar"
              class="avatar"
              :src="user.avatar"
              :alt="user.username + '的头像'"
              onerror="this.onerror=null;this.remove();"
            />
            <div v-else class="text-avatar" :style="getAvatarStyle()">
              {{ user.username ? user.username.charAt(0) : '?' }}
            </div>
          </div>
        </div>
        <div class="user-info">
          <h2 class="username">{{ user.username }}</h2>
          <div v-if="user.email" class="email">{{ user.email }}</div>
          <div class="user-stats">
            <div class="stat-item">
              <span class="stat-value">{{ userStats.votes }}</span>
              <span class="stat-label">已投票</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ userStats.nominations }}</span>
              <span class="stat-label">已提名</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ userStats.favorites }}</span>
              <span class="stat-label">收藏</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="profile-actions">
        <!-- <button class="edit-profile-btn">编辑资料</button> -->
        <button class="change-password-btn">修改密码</button>
      </div>
    </div>
    
    <!-- 最近活动 -->
    <div class="profile-module activities-section">
      <div class="section-header">
        <h2>最近活动</h2>
      </div>
      <div class="module-content">
        <div class="scrollable-anime-container">
          <InfiniteScrollContainer
            :items="activities"
            :has-more="hasMoreActivities"
            :loading-text="'加载更多活动记录...'"
            :virtualization="false"
            @load-more="loadMoreActivities"
          >
            <template #default="{ visibleItems }">
              <div class="activity-list">
                <div v-if="visibleItems.length === 0" class="no-activities">
                  <p>暂无活动记录</p>
                </div>
                <div v-else>
                  <div 
                    v-for="activity in visibleItems" 
                    :key="activity.id"
                    class="activity-item"
                  >
                    <div class="activity-icon">
                      <span>{{ activity.icon }}</span>
                    </div>
                    <div class="activity-content">
                      <p class="activity-text">{{ activity.text }}</p>
                      <p class="activity-time">{{ formatTime(activity.time) }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </InfiniteScrollContainer>
        </div>
      </div>
    </div>
    <!-- 我的投票 -->
    <div class="profile-module my-votes-section">
      <div class="section-header">
          <h2>我的投票</h2>
        </div>
      <div class="module-content">
        <div class="scrollable-anime-container">
          <InfiniteScrollContainer
            :items="votedAnimes"
            :has-more="hasMoreVotedAnimes"
            :loading-text="'加载更多投票记录...'"
            :virtualization="false"
            @load-more="loadMoreVotedAnimes"
          >
            <template #default="{ visibleItems }">
              <!-- <div>投票数据数量: {{ votedAnimes.length }}</div> -->
              <!-- <div>可见数据数量: {{ visibleItems.length }}</div> -->
              <StandardAnimeGrid
                :animes="visibleItems"
                :show-pagination="false"
                :show-vote-button="true"
                :loading="loadingVotedAnimes"
                @show-detail="showAnimeDetail"
                @vote="handleVote"
                empty-message="您还没有投票记录"
                empty-action-text="去投票"
                empty-action-link="/rankings"
              />
            </template>
          </InfiniteScrollContainer>
        </div>
      </div>
    </div>
    <!-- 我的收藏 -->
    <div class="profile-module my-favorites-section">
      <div class="section-header">
          <h2>我的收藏</h2>
        </div>
      <div class="module-content">
        <div class="scrollable-anime-container">
          <InfiniteScrollContainer
            :items="favoriteAnimes"
            :has-more="hasMoreFavoriteAnimes"
            :loading-text="'加载更多收藏记录...'"
            :virtualization="false"
            @load-more="loadMoreFavoriteAnimes"
          >
            <template #default="{ visibleItems }">
              <StandardAnimeGrid
                :animes="visibleItems"
                :show-pagination="false"
                :show-vote-button="true"
                :show-favorite-button="true"
                :loading="loadingFavoriteAnimes"
                @show-detail="showAnimeDetail"
                @vote="handleVote"
                @favorite="handleFavorite"
                empty-message="您还没有收藏记录"
                empty-action-text="去收藏"
                empty-action-link="/all-animes"
              />
            </template>
          </InfiniteScrollContainer>
        </div>
      </div>
    </div>
    
    <!-- 我的提名 -->
    <div class="profile-module my-nominations-section">
      <div class="section-header">
          <h2>我的提名</h2>
        </div>
      <div class="module-content">
        <div class="scrollable-anime-container">
          <InfiniteScrollContainer
            :items="userNominations"
            :has-more="hasMoreUserNominations"
            :loading-text="'加载更多提名记录...'"
            :virtualization="false"
            @load-more="loadMoreUserNominations"
          >
            <template #default="{ visibleItems }">
              <StandardAnimeGrid
                :animes="visibleItems"
                :show-pagination="false"
                :show-vote-button="true"
                :show-nominate-button="false"
                :show-favorite-button="true"
                :loading="loadingUserNominations"
                @show-detail="showAnimeDetail"
                @vote="handleVote"
                @favorite="handleFavorite"
                empty-message="您还没有提名记录"
                empty-action-text="去提名"
                empty-action-link="/nominate"
              />
            </template>
          </InfiniteScrollContainer>
        </div>
      </div>
    </div>
  </div>

  <!-- 动漫详情弹窗 -->
  <AnimeDetailModal 
    v-if="selectedAnime"
    :anime="selectedAnime"
    @close="closeAnimeDetail"
    @vote="handleVote"
    @favorite="handleFavorite"
    @need-login="showLoginModal"
  />

  <!-- 登录提示弹窗 -->
  <LoginPromptModal 
    v-if="showLoginPrompt"
    @close="closeLoginModal"
  />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import StandardAnimeGrid from '../components/StandardAnimeGrid.vue'
import toastService from '../services/toastService'
import { voteForAnime } from '../services/voteService'
import AnimeDetailModal from '../components/AnimeDetailModal.vue'
import LoginPromptModal from '../components/LoginPromptModal.vue'
import InfiniteScrollContainer from '../components/common/InfiniteScrollContainer.vue'
import type { Anime } from '../types/anime'
import { getUserFavoriteIds, batchCheckFavorites } from '../services/favoriteService'
import { getUserNominations } from '../services/animeService'
import { getUserLatestActivities } from '../services/activityService'
import { getCurrentUser } from '../services/userService'
import { getUserVotedAnimes } from '../services/voteService'

// 路由实例
const router = useRouter()

// 用户信息
const user = ref<any>({
  id: '',
  username: '',
  createdAt: '',
  lastLogin: '',
  email: '',
  avatar: ''
})

// 在组件挂载时加载用户数据
onMounted(() => {
  loadUserData()
})

// 用户统计信息
const userStats = ref({
  votes: 0,
  nominations: 0,
  favorites: 0
})

// 用户活动记录
const activities = ref<Array<{
  id: string
  icon: string
  text: string
  time: string
}>>([])

// 用户投票过的动漫 - 后端现在返回完整的Anime对象
const votedAnimes = ref<any[]>([])
const hasMoreVotedAnimes = ref(true)
const loadingVotedAnimes = ref(false)
const votedAnimesPage = ref(1)

// 用户收藏的动漫
const favoriteAnimes = ref<Anime[]>([])
const hasMoreFavoriteAnimes = ref(true)
const loadingFavoriteAnimes = ref(false)
const favoriteAnimesPage = ref(1)

// 提名相关 - 后端现在返回完整的Anime对象
  const userNominations = ref<any[]>([])
const hasMoreUserNominations = ref(true)
const loadingUserNominations = ref(false)
const userNominationsPage = ref(1)

// 每页加载数量
const itemsPerPage = 9

// 选中的动漫（用于详情弹窗）
const selectedAnime = ref<Anime | null>(null)
const showLoginPrompt = ref(false)

// 加载用户数据
const loadUserData = async () => {
  try {
    console.log('开始加载用户数据...')
    // 从接口获取用户信息
    const currentUser = await getCurrentUser()
    if (currentUser) {
      user.value = currentUser
      console.log('用户信息加载成功:', currentUser.username)
      
      // 加载用户统计信息
      loadUserStats()
      console.log('用户统计信息初始化完成')
      
      // 加载用户活动记录
      await loadUserActivities(true)
      console.log('用户活动记录加载完成，数量:', activities.value.length)
      console.log('活动数据:', activities.value)
      
      // 加载用户投票记录
      await loadVotedAnimes(true)
      console.log('用户投票记录加载完成，数量:', votedAnimes.value.length)
      console.log('投票数据:', votedAnimes.value)
      
      // 加载用户收藏记录
      await loadFavoriteAnimes(true)
      console.log('用户收藏记录加载完成，数量:', favoriteAnimes.value.length)
      console.log('收藏数据:', favoriteAnimes.value)
      
      // 加载用户提名记录
      await loadUserNominations(true)
      console.log('用户提名记录加载完成，数量:', userNominations.value.length)
      console.log('提名数据:', userNominations.value)
      
      // 批量检查收藏状态
      if (votedAnimes.value.length > 0 || favoriteAnimes.value.length > 0 || userNominations.value.length > 0) {
        await checkFavoritesForAllAnimes()
        console.log('收藏状态检查完成')
      }
    } else {
      console.log('用户未登录')
      // 用户未登录，跳转到登录页面
      router.push('/login')
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
    // 跳转到登录页面
    // router.push('/login')
  }
}

// 检查所有动漫列表的收藏状态
  const checkFavoritesForAllAnimes = async () => {
    try {
      // 收集所有需要检查收藏状态的动漫ID
      const animeIds = new Set<number>()
      
      // 从收藏列表中收集ID
      if (favoriteAnimes.value) {
        favoriteAnimes.value.forEach(anime => {
          if (anime.id) animeIds.add(Number(anime.id))
        })
      }
      
      // 从投票列表中收集ID - 后端现在返回的是完整的Anime对象
      if (votedAnimes.value) {
        votedAnimes.value.forEach(anime => {
          if (anime.id) animeIds.add(Number(anime.id))
        })
      }
      
      // 从提名列表中收集ID - 后端现在返回的是完整的Anime对象
      if (userNominations.value) {
        userNominations.value.forEach(anime => {
          if (anime.id) animeIds.add(Number(anime.id))
        })
      }
      
      // 如果没有动漫ID，直接返回
      if (animeIds.size === 0) return
      
      // 调用批量检查收藏状态的API，直接获取收藏状态映射
      // batchCheckFavorites返回的是Record<number, boolean>类型
      const favoritesMap = await batchCheckFavorites(Array.from(animeIds))
      
      // 更新收藏列表的收藏状态
      if (favoriteAnimes.value) {
        favoriteAnimes.value.forEach(anime => {
          const id = Number(anime.id)
          if (id) {
            anime.isFavorite = true // 收藏列表中的项目都是已收藏的
          }
        })
      }
      
      // 更新投票列表的收藏状态 - 使用Anime类型
      if (votedAnimes.value) {
        votedAnimes.value.forEach(anime => {
          const id = Number(anime.id)
          if (id) {
            anime.isFavorite = favoritesMap[id] || false
          }
        })
      }
      
      // 更新提名列表的收藏状态 - 使用Anime类型
      if (userNominations.value) {
        userNominations.value.forEach(anime => {
          const id = Number(anime.id)
          if (id) {
            anime.isFavorite = favoritesMap[id] || false
          }
        })
      }
    } catch (error) {
      console.error('检查收藏状态失败:', error)
    }
  }

// 加载用户统计信息
const loadUserStats = () => {
  // 初始化空的统计信息
  userStats.value = {
    votes: 0,
    nominations: 0,
    favorites: 0
  }
}

// 加载用户提名记录
  const loadUserNominations = async (reset = false) => {
    if (reset) {
      userNominationsPage.value = 1
      hasMoreUserNominations.value = true
    }
    
    if (loadingUserNominations.value || !hasMoreUserNominations.value) return
    
    loadingUserNominations.value = true
    try {
      // 调用API获取用户提名记录，使用分页查询
      // 注意：后端现在直接返回Anime对象列表
      const response = await getUserNominations(userNominationsPage.value, itemsPerPage)
      
      // 如果没有提名记录，清空列表
      if (!response || !response.data || response.data.length === 0) {
        if (reset) {
          userNominations.value = []
        }
        userStats.value.nominations = response?.total || 0
        hasMoreUserNominations.value = false
        return
      }
      
      // 更新提名统计
      userStats.value.nominations = response.total
      
      // 后端已直接返回Anime[]类型，无需类型断言
      const newAnimes = response.data
      
      // 更新提名列表
      if (reset) {
        userNominations.value = newAnimes
      } else {
        userNominations.value = [...userNominations.value, ...newAnimes]
      }
      
      // 检查是否还有更多数据
      hasMoreUserNominations.value = userNominations.value.length < response.total
      
      // 更新收藏状态
      await checkFavoritesForAllAnimes()
    } catch (error) {
      console.error('加载用户提名记录失败:', error)
      if (reset) {
        userNominations.value = []
        userStats.value.nominations = 0
      }
    } finally {
      loadingUserNominations.value = false
    }
  }

// 加载更多提名记录
const loadMoreUserNominations = () => {
  if (!loadingUserNominations.value && hasMoreUserNominations.value) {
    userNominationsPage.value++
    loadUserNominations(false)
  }
}

// 活动记录分页相关状态
const activitiesPage = ref(1)
const hasMoreActivities = ref(true)
const loadingActivities = ref(false)

// 加载用户活动记录
const loadUserActivities = async (reset = false) => {
  if (reset) {
    activitiesPage.value = 1
    hasMoreActivities.value = true
  }
  
  if (loadingActivities.value || !hasMoreActivities.value) return
  
  loadingActivities.value = true
  try {
    // 从后端API获取用户活动记录，使用分页查询
    const response = await getUserLatestActivities(activitiesPage.value, itemsPerPage);
    
    if (response && response.data && response.data.length > 0) {
      // 将后端返回的活动记录转换为前端需要的格式
      const formattedActivities = response.data.map(activity => ({
        id: activity.id.toString(),
        icon: activity.activityType === 'vote' ? '👍' : activity.activityType === 'nomination' ? '🏆' : '⭐',
        text: `您${activity.activityContent}`,
        time: activity.activityTime
      }));
      
      // 更新活动列表
      if (reset) {
        activities.value = formattedActivities
      } else {
        activities.value = [...activities.value, ...formattedActivities]
      }
      
      // 检查是否还有更多数据
      hasMoreActivities.value = activities.value.length < response.total
    } else {
      // 如果没有活动记录，显示空状态
      if (reset) {
        activities.value = []
      }
      hasMoreActivities.value = false
    }
  } catch (error) {
    console.error('加载用户活动记录失败:', error);
    if (reset) {
      activities.value = []
    }
    hasMoreActivities.value = false
  } finally {
    loadingActivities.value = false
  }
}

// 加载更多活动记录
const loadMoreActivities = () => {
  if (!loadingActivities.value && hasMoreActivities.value) {
    activitiesPage.value++
    loadUserActivities(false)
  }
}

// 加载用户投票记录
const loadVotedAnimes = async (reset = false) => {
  if (reset) {
    votedAnimesPage.value = 1
    hasMoreVotedAnimes.value = true
  }
  
  if (loadingVotedAnimes.value || !hasMoreVotedAnimes.value) return
  
  loadingVotedAnimes.value = true
  try {
      // 调用API获取用户投票记录，使用分页查询
      // 注意：后端现在直接返回Anime对象列表
      const response = await getUserVotedAnimes(votedAnimesPage.value, itemsPerPage)
    
      // 如果没有投票记录，清空列表
      if (!response || !response.data || response.data.length === 0) {
        if (reset) {
          votedAnimes.value = []
        }
        userStats.value.votes = response?.total || 0
        hasMoreVotedAnimes.value = false
        return
      }
    
      // 更新投票统计
      userStats.value.votes = response.total
    
      // 后端已直接返回Anime[]类型，无需类型断言
      const newAnimes = response.data
      
      // 更新投票列表
      if (reset) {
        votedAnimes.value = newAnimes
      } else {
        votedAnimes.value = [...votedAnimes.value, ...newAnimes]
      }
    
    // 检查是否还有更多数据
      hasMoreVotedAnimes.value = votedAnimes.value.length < response.total
      
      // 更新收藏状态
      await checkFavoritesForAllAnimes()
  } catch (error) {
    console.error('加载用户投票记录失败:', error)
    if (reset) {
      votedAnimes.value = []
      userStats.value.votes = 0
    }
  } finally {
    loadingVotedAnimes.value = false
  }
}

// 加载更多投票记录
const loadMoreVotedAnimes = () => {
  if (!loadingVotedAnimes.value && hasMoreVotedAnimes.value) {
    votedAnimesPage.value++
    loadVotedAnimes(false)
  }
}

// 加载用户收藏
const loadFavoriteAnimes = async (reset = false) => {
  if (reset) {
    favoriteAnimesPage.value = 1
    hasMoreFavoriteAnimes.value = true
  }
  
  if (loadingFavoriteAnimes.value || !hasMoreFavoriteAnimes.value) return
  
  loadingFavoriteAnimes.value = true
  try {
    // 直接获取用户收藏的完整动漫信息列表
    const favoriteResponse = await getUserFavoriteIds(favoriteAnimesPage.value, itemsPerPage)
    
    // 如果没有收藏记录，清空列表
    if (!favoriteResponse || !favoriteResponse.data || favoriteResponse.data.length === 0) {
      if (reset) {
        favoriteAnimes.value = []
      }
      userStats.value.favorites = favoriteResponse?.total || 0
      hasMoreFavoriteAnimes.value = false
      return
    }
    
    // 更新收藏统计
    userStats.value.favorites = favoriteResponse.total
    
    // 为收藏的动漫标记为已收藏，并确保票数数据正确初始化
    const detailedAnimes = favoriteResponse.data.map(anime => ({
      ...anime,
      isFavorite: true,
      votes: anime.votes || 0, // 确保 votes 字段存在并初始化为0
      favorites: anime.favorites || 0 // 确保 favorites 字段存在并初始化为0
    }))
    
    // 更新收藏列表
    if (reset) {
      favoriteAnimes.value = detailedAnimes
    } else {
      favoriteAnimes.value = [...favoriteAnimes.value, ...detailedAnimes]
    }
    
    // 检查是否还有更多数据
    hasMoreFavoriteAnimes.value = favoriteAnimes.value.length < favoriteResponse.total
  } catch (error) {
    console.error('加载用户收藏失败:', error)
    if (reset) {
      favoriteAnimes.value = []
      userStats.value.favorites = 0
    }
  } finally {
    loadingFavoriteAnimes.value = false
  }
}

// 加载更多收藏记录
const loadMoreFavoriteAnimes = () => {
  if (!loadingFavoriteAnimes.value && hasMoreFavoriteAnimes.value) {
    favoriteAnimesPage.value++
    loadFavoriteAnimes(false)
  }
}

// 格式化时间
const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - date.getTime())
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else if (diffDays < 30) {
    const weeks = Math.floor(diffDays / 7)
    return `${weeks}周前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  }
}

// 显示动漫详情弹窗
const showAnimeDetail = (anime: Anime) => {
  selectedAnime.value = anime
}

// 处理投票
const handleVote = async (animeId: number) => {
  try {
    // 调用投票API
    const success = await voteForAnime(animeId)
    
    if (success) {
      // 刷新用户的投票记录
      await loadVotedAnimes(true)
      // 刷新用户的收藏记录，确保获取最新的投票数
      await loadFavoriteAnimes(true)
      // 刷新用户的提名记录，确保获取最新的投票数
      await loadUserNominations(true)
      
      // 更新所有列表中的动漫投票状态
      const updateAnimeVoteStatus = (animes: any[]) => {
        const anime = animes.find(a => a.id === animeId)
        if (anime) {
          anime.votes = (anime.votes || 0) + 1
          anime.userVoted = true
          return anime.title
        }
        return null
      }

      let animeTitle = updateAnimeVoteStatus(votedAnimes.value)
      if (!animeTitle) animeTitle = updateAnimeVoteStatus(favoriteAnimes.value)
      if (!animeTitle) animeTitle = updateAnimeVoteStatus(userNominations.value)
      
      // 添加活动记录并保持最多5条
      const newActivity = {
        id: Date.now().toString(),
        text: `对《${animeTitle || '未知动漫'}》进行了投票`,
        icon: '👍',
        time: new Date().toISOString()
      }
      activities.value.unshift(newActivity)
      if (activities.value.length > 5) {
        activities.value.pop()
      }
      
      toastService.success('投票成功！')
    } else {
      toastService.error('投票失败，请重试')
    }
  } catch (error) {
    console.error('投票失败:', error)
    toastService.error('投票失败，请重试')
  }
}

// 处理收藏
const handleFavorite = async (eventData: number | { animeId: number, isFavorited: boolean }) => {
  // 处理不同格式的输入
  let animeId: number;
  let isFavorited: boolean | null = null;
  
  if (typeof eventData === 'object' && eventData !== null) {
    // 新格式 - 对象包含animeId和isFavorited
    animeId = eventData.animeId;
    isFavorited = eventData.isFavorited;
  } else {
    // 兼容旧格式 - 直接传入animeId
    animeId = Number(eventData);
  }
  
  // 检查用户是否已登录
  const user = localStorage.getItem('user')
  if (!user) {
    // 显示登录提示
    toastService.info('请先登录后再收藏！');
    return
  }
  
  try {
    // 从favoriteService导入checkFavorite, addFavorite, removeFavorite函数
    const { checkFavorite, addFavorite, removeFavorite } = await import('../services/favoriteService')
    
    if (isFavorited === null) {
      // 如果没有提供isFavorited，检查当前收藏状态
      isFavorited = await checkFavorite(animeId);
    }
    
    if (isFavorited) {
      // 取消收藏
      await removeFavorite(animeId)
    } else {
      // 添加收藏
      await addFavorite(animeId)
    }
    
    // 刷新用户的收藏记录
    await loadFavoriteAnimes(true)
    
    // 更新其他列表中的动漫收藏状态
    const updateAnimeFavoriteStatus = (animes: any[]) => {
      const anime = animes.find(a => a.id === animeId)
      if (anime) {
        // 更新为操作后的收藏状态
      anime.isFavorite = !isFavorited; // 因为isFavorited是操作前的状态，操作后应该是相反的值
        return anime.title
      }
      return null
    }

    let animeTitle = updateAnimeFavoriteStatus(favoriteAnimes.value)
    if (!animeTitle) animeTitle = updateAnimeFavoriteStatus(votedAnimes.value)
    if (!animeTitle) animeTitle = updateAnimeFavoriteStatus(userNominations.value)
    
    // 添加活动记录并保持最多5条
    const newActivity = {
      id: Date.now().toString(),
      text: `对《${animeTitle || '未知动漫'}》${isFavorited ? '取消' : '添加'}了收藏`,
      icon: '⭐',
      time: new Date().toISOString()
    }
    activities.value.unshift(newActivity)
    if (activities.value.length > 5) {
      activities.value.pop()
    }
  } catch (error) {
    console.error('更新收藏状态失败:', error)
  }
}

// 关闭动漫详情弹窗
const closeAnimeDetail = () => {
  selectedAnime.value = null
}

// 显示登录提示
const showLoginModal = () => {
  showLoginPrompt.value = true
}

// 关闭登录提示
const closeLoginModal = () => {
  showLoginPrompt.value = false
}

// 根据用户名生成文字头像的样式
const getAvatarStyle = (): Record<string, string> => {
  const colors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#F9CA24', '#6C5CE7',
    '#A29BFE', '#FD79A8', '#00B894', '#FDCB6E', '#6C5CE7'
  ];
  
  // 使用用户名的字符码来选择颜色，确保相同用户名总是有相同的颜色
  const hash = user.value.username 
    ? user.value.username.split('').reduce((acc: number, char: string) => acc + char.charCodeAt(0), 0)
    : 0;
  const color = colors[hash % colors.length];
  
  return {
    backgroundColor: color,
    width: '120px',
    height: '120px',
    borderRadius: '50%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontSize: '48px',
    fontWeight: 'bold',
    color: 'white',
    textAlign: 'center'
  };
}

// 组件挂载时加载用户数据
onMounted(() => {
  loadUserData()
})
</script>

<style scoped>
/* 页面容器 */
.profile-page {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 16px;
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 32px 16px;
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header h1 {
  font-size: 2.25rem;
  font-weight: 700;
  color: #1C1C1E;
  letter-spacing: -0.02em;
  line-height: 1.1;
}

/* 用户信息卡片 */
.user-profile-card {
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 32px;
  margin-bottom: 40px;
  animation: fadeInUp 0.8s ease-out;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  gap: 32px;
}

.avatar-container {
  position: relative;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #F2F2F7;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.avatar-container {
    position: relative;
  }
  
  .avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid #F2F2F7;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.2s ease;
  }
  
  .avatar:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  }
  
  .user-info {
    flex: 1;
  }

.username {
  font-size: 1.75rem;
  font-weight: 600;
  color: #1C1C1E;
  margin-bottom: 8px;
  letter-spacing: -0.01em;
}

.email {
  font-size: 1rem;
  color: #6C6C70;
  margin-bottom: 16px;
}

.user-stats {
  display: flex;
  gap: 40px;
  padding-top: 16px;
  border-top: 1px solid #E5E5EA;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.stat-value {
  font-size: 1.75rem;
  font-weight: 700;
  color: #007AFF;
}

.stat-label {
  font-size: 0.875rem;
  color: #6C6C70;
  margin-top: 4px;
}

.profile-actions {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
}

.edit-profile-btn,
.change-password-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 12px;
  background-color: #F2F2F7;
  color: #1C1C1E;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.875rem;
  font-weight: 500;
  min-width: 120px;
}

.edit-profile-btn:hover,
.change-password-btn:hover {
  background-color: #E5E5EA;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 活动记录区域 */
.activity-section,
.my-votes-section,
.my-favorites-section {
  margin-bottom: 60px;
  animation: fadeInUp 1s ease-out;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1C1C1E;
  letter-spacing: -0.01em;
}

.activity-list {
    background-color: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .scrollable-grid {
    background-color: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    padding-bottom: 10px;
  }
  
  .scrollable-grid::-webkit-scrollbar {
    height: 6px;
  }
  
  .scrollable-grid::-webkit-scrollbar-track {
    background: #F2F2F7;
    border-radius: 3px;
  }
  
  .scrollable-grid::-webkit-scrollbar-thumb {
    background: #007AFF;
    border-radius: 3px;
  }
  
  .scrollable-grid::-webkit-scrollbar-thumb:hover {
    background: #0051D5;
  }

.no-activities,
.no-votes,
.no-favorites {
  text-align: center;
  padding: 60px 20px;
  color: #6C6C70;
  font-size: 1rem;
}

.vote-now-btn,
.favorite-now-btn {
  display: inline-block;
  margin-top: 16px;
  padding: 10px 20px;
  background-color: #007AFF;
  color: white;
  border-radius: 12px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.2s ease;
}

.vote-now-btn:hover,
.favorite-now-btn:hover {
  background-color: #0062CC;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.25);
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #E5E5EA;
  transition: all 0.2s ease;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-item:hover {
  background-color: #F9F9F9;
  border-radius: 12px;
  padding: 16px 20px;
  margin: 0 -20px;
}

.activity-icon {
  font-size: 20px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #F2F2F7;
  border-radius: 50%;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 1rem;
  color: #1C1C1E;
  margin-bottom: 4px;
  line-height: 1.5;
}

.activity-time {
  font-size: 0.875rem;
  color: #8E8E93;
}

/* 个人资料模块通用样式 */
.profile-module {
  background-color: #FFFFFF;
  border-radius: 16px;
  border: 1px solid #E5E5EA;
  padding: 24px;
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.profile-module:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.section-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #F2F2F7;
}

.section-header h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1C1C1E;
  margin: 0;
}

.module-content {
  /* 模块内容容器 */
}

/* 动漫容器 */
.scrollable-anime-container {
  padding: 8px;
  height: 500px; /* 确保容器有固定高度，以便滚动工作正常 */
  overflow: hidden; /* 隐藏溢出内容 */
  position: relative;
}

/* 移除嵌套网格样式，让StandardAnimeGrid组件自己控制布局 */
.scrollable-anime-container > div {
  padding-bottom: 10px;
}

/* 空状态样式优化 */
.module-content > div .empty-state {
  padding: 40px 20px;
  text-align: center;
  color: #8E8E93;
}

.module-content > div .empty-state p {
  margin-bottom: 16px;
  font-size: 1rem;
}

.module-content > div .empty-state button {
  background-color: #007AFF;
  color: white;
  border: none;
  padding: 10px 24px;
  border-radius: 8px;
  font-size: 0.9375rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.module-content > div .empty-state button:hover {
  background-color: #0062CC;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.25);
}

/* 响应式设计 */
/* 移除嵌套网格的响应式样式 */

@media (max-width: 768px) {
  .profile-page {
    padding: 16px;
  }
  
  .page-header {
    margin-bottom: 32px;
    padding: 24px 16px;
  }
  
  .page-header h1 {
    font-size: 1.75rem;
  }
  
  .user-profile-card {
    padding: 24px;
  }
  
  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 24px;
  }
  
  .username {
    font-size: 1.5rem;
  }
  
  .user-stats {
    justify-content: center;
    gap: 24px;
  }
  
  .stat-value {
    font-size: 1.5rem;
  }
  
  .profile-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .edit-profile-btn,
  .change-password-btn {
    width: 100%;
    max-width: 200px;
  }
  
  .profile-module {
    padding: 20px;
    margin-bottom: 20px;
  }
  
  .section-header {
    margin-bottom: 16px;
    padding-bottom: 10px;
  }
  
  .section-header h2 {
    font-size: 1.25rem;
  }
  
  .activity-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .activity-icon {
    margin-bottom: 8px;
  }
  

  
  .scrollable-anime-container {
    padding: 4px;
  }
  
  /* 空状态响应式优化 */
  .scrollable-anime-container > div .empty-state {
    padding: 30px 16px;
  }
}

@media (max-width: 480px) {
    
    .profile-page {
      padding: 12px;
    }
  
  .page-header {
    padding: 20px 12px;
    border-radius: 16px;
  }
  
  .page-header h1 {
    font-size: 1.5rem;
  }
  
  .user-profile-card {
    padding: 20px;
    border-radius: 16px;
  }
  
  .user-stats {
    flex-direction: column;
    gap: 16px;
  }
  
  .stat-item {
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
  }
  
  .activity-list,
  .voted-animes {
    padding: 20px 16px;
  }
  
  .anime-grid {
    grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
    gap: 12px;
  }
}

/* 高对比度模式支持 */
@media (prefers-contrast: high) {
  .page-header {
    background-color: #ffffff;
    border: 2px solid #000000;
  }
  
  .user-profile-card {
    background-color: #ffffff;
    border: 2px solid #000000;
  }
  
  .activity-list,
.voted-animes,
.favorite-animes {
  background-color: #ffffff;
  border: 2px solid #000000;
}
  
  .edit-profile-btn,
  .change-password-btn {
    border: 2px solid #000000;
  }
  
  .vote-now-btn,
.favorite-now-btn {
  border: 2px solid #000000;
}
}

/* 减少动画偏好支持 */
@media (prefers-reduced-motion: reduce) {
  .page-header,
  .user-profile-card,
  .activity-section,
  .my-votes-section {
    animation: none;
  }
  
  .avatar:hover,
  .edit-profile-btn:hover,
  .change-password-btn:hover,
  .vote-now-btn:hover {
    transform: none;
  }
  
  .activity-item:hover {
    padding: 16px 0;
    margin: 0;
  }
}
</style>